package com.decent.ejfadmin.report.service.impl;

import com.decent.ejfadmin.common.bean.ExkDailyReportBean;
import com.decent.ejfadmin.common.bean.MessageBean;
import com.decent.ejfadmin.common.enums.ExkChannelPlat;
import com.decent.ejfadmin.job.ExkProfitDailyJob;
import com.decent.ejfadmin.report.dao.CollectCardProfitDailyReportDao;
import com.decent.ejfadmin.report.service.CollectCardProfitDailyReportService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author weicx
 * @date 2018/08/01
 */
@Service
public class CollectCardProfitDailyReportServiceImpl implements CollectCardProfitDailyReportService {
    @Autowired
    private CollectCardProfitDailyReportDao collectCardProfitDailyReportDao;

    /**
     * 销卡利润统计数据写入
     *
     * @param startTime 开始时间
     */
    @Override
    public void writeRecord(Date startTime) {
        Date endTime = DateUtils.addMilliseconds(DateUtils.addDays(startTime, 1), -1);
        //汇总数据
        List<ExkDailyReportBean> exkDailyReportBeans = collectCardProfitDailyReportDao.dailyJobRecord(startTime, endTime);
        if (exkDailyReportBeans.isEmpty()) {
            return;
        }
        //查询代充费用
        HashMap<String, BigDecimal> data = new HashMap<>(16);
        ExkProfitDailyJob.queryChargeFee(startTime, data);
        //计算费用及利润并入库
        for (int i = 0; i < exkDailyReportBeans.size(); i++) {
            ExkDailyReportBean exkDailyReportBean = exkDailyReportBeans.get(i);
            //易缴费在易销卡的会员编号
            String key = ExkProfitDailyJob.CUSTOMER_NO_REFLECT.get(exkDailyReportBean.getAgentNo()) + exkDailyReportBean.getProductType();
            exkDailyReportBean.setChargeFee(Optional.ofNullable(data.get(key)).orElse(BigDecimal.ZERO));
            data.remove(key);
            BigDecimal profit = exkDailyReportBean.getSales().subtract(exkDailyReportBean.getCosts()).subtract(exkDailyReportBean.getChargeFee());
            exkDailyReportBean.setProfit(profit);
            exkDailyReportBean.setDate(startTime);
            collectCardProfitDailyReportDao.addReportRecord(exkDailyReportBean);
        }
    }

    /**
     * 查询销卡利润
     *
     * @param startTime      查询开始时间
     * @param endTime        查询结束时间
     * @param exkChannelPlat 销卡渠道
     * @return
     */
    @Override
    public List<ExkDailyReportBean> queryDailyReport(String startTime, String endTime, ExkChannelPlat exkChannelPlat) {
        LocalDate now = LocalDate.now();
        LocalDate begin = LocalDate.parse(startTime.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate end = LocalDate.parse(endTime.substring(0, 10), DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        boolean isIncludeToday = (begin.isEqual(now) || begin.isBefore(now)) && (end.isEqual(now) || end.isAfter(now));
        //获取当日数据
        if (isIncludeToday) {
            writeRecord(DateUtils.truncate(new Date(), Calendar.DATE));
        }
        List<ExkDailyReportBean> totalResult = Optional.ofNullable(collectCardProfitDailyReportDao.queryDailyReport(exkChannelPlat, startTime, endTime)).orElse(Collections.emptyList());
        combineData(totalResult);
        return totalResult;
    }

    /**
     * 最终数据组装
     *
     * @param totalResult 待返回的结果
     */
    private void combineData(List<ExkDailyReportBean> totalResult) {
        BigDecimal initPrice = BigDecimal.ZERO;
        ExkDailyReportBean total = new ExkDailyReportBean(0, 0, initPrice
                , initPrice, initPrice, initPrice, initPrice
                , initPrice, initPrice, initPrice);
        for (int i = 0; i < totalResult.size(); i++) {
            ExkDailyReportBean exkDailyReportBean = totalResult.get(i);
            //利润=销卡价格-收卡价格-销卡处理费用-代充费用-闲鱼返点
            BigDecimal profit = exkDailyReportBean.getSales().subtract(exkDailyReportBean.getCosts()).subtract(exkDailyReportBean.getSalesFee()).subtract(exkDailyReportBean.getChargeFee()).subtract(exkDailyReportBean.getXianyuCommission());

            //利润率=利润/面值
            BigDecimal profitRate = BigDecimal.ZERO;
            if (BigDecimal.ZERO.compareTo(exkDailyReportBean.getTotalFace()) < 0) {
                profitRate = profit.divide(exkDailyReportBean.getTotalFace(), 4, BigDecimal.ROUND_HALF_UP);
            }
            exkDailyReportBean.setProfitRate(profitRate.multiply(new BigDecimal("100")));
            total.setSuccessTotal(total.getSuccessTotal() + exkDailyReportBean.getSuccessTotal());
            total.setTotalFace(total.getTotalFace().add(exkDailyReportBean.getTotalFace()));
            total.setFailTotal(total.getFailTotal() + exkDailyReportBean.getFailTotal());
            total.setSales(total.getSales().add(exkDailyReportBean.getSales()));
            total.setCosts(total.getCosts().add(exkDailyReportBean.getCosts()));
            total.setSalesFee(total.getSalesFee().add(exkDailyReportBean.getSalesFee()));
            total.setChargeFee(total.getChargeFee().add(exkDailyReportBean.getChargeFee()));
            total.setProfit(total.getProfit().add(exkDailyReportBean.getProfit()));
            total.setXianyuCommission(total.getXianyuCommission().add(exkDailyReportBean.getXianyuCommission()));
        }
        BigDecimal totalFace = total.getTotalFace();
        if (totalFace.compareTo(BigDecimal.ZERO) > 0) {
            total.setProfitRate(total.getProfit().divide(totalFace, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")));
        }
        totalResult.add(total);
    }

    /**
     * 利润统计
     *
     * @param startTime 统计时间
     * @return
     */
    @Override
    public MessageBean profitDailyReport(String startTime) throws ParseException {
        Date reportTime = DateUtils.parseDate(startTime + " 00:00:00", "yyyy-MM-dd hh:mm:ss");
        writeRecord(reportTime);
        return MessageBean.success();
    }
}
